package com.evosoft.dao;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.evosoft.excepciones.NotEntityFoundException;
import com.evosoft.model.Empresa;
import com.evosoft.model.Persona;
import java.util.ArrayList;
import java.util.List;

public class PersonaDAO  extends GenericDao<Persona>{
	
	
	private static final long serialVersionUID = 1L;
	private static PersonaDAO instance;

    public PersonaDAO() {
        super(Persona.class);
    }

    public synchronized static PersonaDAO getInstance() {
        if(instance == null){
            instance = new PersonaDAO();
        }
        
        return instance;
    }
	
    
    public Persona findByUsuario(String usuario, EntityManager em) throws NotEntityFoundException {
    	
    	Query query = em.createQuery("SELECT p FROM Persona p WHERE p.usuario=:usuario");
        query.setParameter("usuario", usuario);
        
        Persona entity = null;

        try {
            entity = (Persona) query.getSingleResult();
        } catch (Exception e) {
        	throw (new NotEntityFoundException());
        }

        return entity;
    	    	    	
    }
    
    public List<Persona> obtenerPersonasPorRol(int id, EntityManager em) throws NotEntityFoundException {
        Query query = em.createQuery("SELECT p FROM Persona p WHERE p.rol.id=:id");
        query.setParameter("id", id);
        List<Persona> entity = new ArrayList<Persona>();

        try {
            entity = (List) query.getResultList();
        } catch (Exception e) {
        	throw (new NotEntityFoundException());
        }

        return entity;
    }

    public List<Persona> obtenerPersonasPorEmpresa(int idEmpresa, EntityManager em) throws NotEntityFoundException {
        Query query = em.createQuery("SELECT p FROM Persona p WHERE p.empresa.id=:idEmpresa");
        query.setParameter("idEmpresa", idEmpresa);
        
        List<Persona> personas = new ArrayList<Persona>();
        
        try {
            personas = (List) query.getResultList();
        } catch (Exception e) {
        	throw (new NotEntityFoundException());
        }

        return personas;
    }

}
